package com.zhiwei.common.config;

import com.zhiwei.common.constant.DatabaseConstants;
import com.zhiwei.common.util.ReflectionUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自定义 Mybatis插件：
 * 自动设置 create_time、update_time。
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MybatisUpdateInterceptor implements Interceptor {


    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        Date nowTime = new Date();

        //新增
        if (SqlCommandType.INSERT.equals(sqlCommandType)) {
            ReflectionUtils.setPropertyValue(parameter, DatabaseConstants.CREATE_TIME, nowTime);
            ReflectionUtils.setPropertyValue(parameter, DatabaseConstants.CREATE_USER, SecurityContext.getUsername());
        }

        //更新
        if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
            ReflectionUtils.setPropertyValue(parameter, DatabaseConstants.UPDATE_TIME, nowTime);
            ReflectionUtils.setPropertyValue(parameter, DatabaseConstants.UPDATE_USER, SecurityContext.getUsername());
        }
        return invocation.proceed();
    }
}


